<template>
  <van-button 
    :icon="isCollected ? 'star':'star-o'"  
    :color="isCollected ? '#3296fa':'#777'" 
    plain
    :loading="loading"
    @click="onArticleCollect" 
  />
</template>

<script>
import {addCollect,deleteCollect} from '@/api/article'
  export default {
    data() {
      return {
        loading: false  // 节流阀
      }
    },
    model:{
      prop:'isCollected',
      event:'update-iscollected'
    },
    props: {
      // 用于接收是否收藏了
      isCollected: {
        type: Boolean,
        required:true 
      },
      // value: {
      //   type: Boolean,
      //   required:true 
      // },
      // 接收文章ID
      articleId:{
        type:[String,Number,Object],
        required:true
      }
    },
    methods: {
      async onArticleCollect() {
        // 没登录不可以收藏
        if(!this.$store.state.user){
          return this.$router.push('/login?redirect='+this.$route.path)
        }
        this.loading = true
        try {
          // 判断收藏还是取消
          if(this.isCollected){
            // 要取消
            await deleteCollect(this.articleId)
          }else{
            // 要收藏
            await addCollect(this.articleId)
          }
          this.$toast.success(this.isCollected ? '取消成功':'收藏成功')
          this.$emit('update-iscollected',!this.isCollected)
        } catch (error) {
          this.$toast.fail(this.isCollected ? '取消收藏失败':'收藏失败')
        }
        this.loading = false
      }
    },
  }
</script>

<style lang="less" scoped>
.van-button--default{
  border:none;
}
</style>